<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 限时秒杀接口
 */
class Spike extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     * 
     */
    public function index()
    {
        $time = $this->request->post('time');
        $res = Db::name('Spike')
            ->where(function ($query) use($time){
                if($time == 1){
                    $query->where('starttime','<',time())->where('endtime','>',time());
                }
                if($time == 2){
                    $query->where('starttime','>',time());
                }
                if($time == 3){
                    $query->where('endtime','<',time());
                }
            })
            ->select();
        $starttime = Db::name('spike')->where('endtime','>',time())->where('starttime','>',time())->min('starttime');
        $time = time();
        foreach ($res as $k=>$v){
            if($v['starttime'] > $time){
                $res[$k]['state'] = 0;
            }elseif ($v['starttime'] < $time && $v['endtime'] > $time){
                $res[$k]['state'] = 1;
            }else{
                $res[$k]['state'] = 2;
            }
        }
        return json_encode(array('res'=>$res,'time'=>$starttime-$time));
    }
    public function detail(){
        $id = $this->request->post('id');
        $res = Db::name('spike')->where('id',$id)->find();
        $time = time();
        if($res['starttime'] > $time){
            $res['state'] = 0;
        }elseif ($res['starttime'] < $time && $res['endtime'] > $time){
            $res['state'] = 1;
        }else{
            $res['state'] = 2;
        }
        return json_encode(array('res'=>$res,'starttime'=>$res['starttime']-$time,'endtime'=>$res['endtime']-$time));
    }
    public function order(){
        $params = $this->request->post();
        $count = Db::name('spike')->where('id',$params['goods_id'])->value('num');
        if($count < $params['num']){
            return 402;
        }
        $people = model('People')->people($params['openid']);
        $order_no = date('Ymd')."XTD".substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        array_shift($params);
        $params['people_id'] = $people['id'];
        $params['order_no'] = $order_no;
        $params['createtime'] = time();
        $res = Db::name('order')->insert($params);
        $id = Db::name('order')->getLastInsID();
        $this->get_qrcode($id);
        return $res?$order_no:400;
    }
    //获取access_token
    public function get_access_token(){
        $appid = 'wx4e96723bd56676c3';
        $secret = '6b78f796bd45d534909c1bcc9d443875';
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
        return $this->curl_get($url);
    }

    public function curl_get($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);
        return $err?$err:$data;
    }
    //获得二维码
    public function get_qrcode($id) {
        $file = ROOT_PATH."log.txt";
//        header('content-type:image/gif');
//        header('content-type:image/png');//格式自选，不同格式貌似加载速度略有不同，想加载更快可选择jpg
        header('content-type:image/jpg');
        $path="pages/order/order?oid=".$id;
        $width=430;
        $data='{"path":"'.$path.'","width":'.$width.'}';
        $access = json_decode($this->get_access_token(),true);
        $content = "时间： ".date("Y-m-d H:i:s",time())."\r\n"."access_token： ".json_encode($access)."\r\n"."\r\n\r\n\r\n";
        file_put_contents($file, $content,FILE_APPEND);
        $access_token= $access['access_token'];
//        dump($data);exit;
        $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" . $access_token;
        $da = $this->get_http_array($url,$data);
        $name = time();
        $reslut = file_put_contents(ROOT_PATH . 'public' . DS . 'uploads/erweima/'.$name.'.jpg',$da);
        if($reslut){
            $ewm = '/uploads/erweima/'.$name.'.jpg';
            Db::name('order')->where('id',$id)->update(['ewm'=>$ewm]);
        }

        return $reslut?'uploads/erweima/'.$name.'.jpg':json_encode(400);
        //file_put_contents('./Uploads/qrcode/code-'.$name.'.jpg',$da);
        //这里强调显示二维码可以直接写该访问路径，同时也可以使用curl保存到本地，详细用法可以加群或者加我扣扣
    }
    public function get_http_array($url,$data) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $tmpInfo = curl_exec($ch);
        $error = curl_errno($ch);
        curl_close($ch);
        if ($error) {
            return $error;
        }else{
            return $tmpInfo;
        }
    }
}
